
package com.kugou.game.sdk.utils;

import com.kugou.game.sdk.core.SDKControler;
import com.kugou.game.sdk.statistics.StaticsManager;

import android.content.Context;
import android.text.TextUtils;

import java.lang.Thread.UncaughtExceptionHandler;

/**
 * 描述:异常处理类
 * 
 * @author ljc
 * @since 2014-12-3 上午10:55:17
 */
public class AppUncaughtExceptionHandler implements UncaughtExceptionHandler {

    private Context mContext;

    private UncaughtExceptionHandler mDefaultHandler;

    public AppUncaughtExceptionHandler(Context context) {
        this.mContext = context;
        setCrashReported(false);
        mDefaultHandler = Thread.getDefaultUncaughtExceptionHandler();
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
        try {
            if (ex != null && !isCrashReported()) {
                setCrashReported(true);

                handleException(ex);
                mDefaultHandler.uncaughtException(thread, ex);
                Thread.setDefaultUncaughtExceptionHandler(null);

                Thread.sleep(1000);

                AppUtil.gc();
                // 让游戏彻底退出
                SDKControler.release(true);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void handleException(Throwable ex) {
        if (ex != null) {
            final String crashReport = AppUtil.getCrashReport(ex);

            // 非调试模式才上传崩溃统计
            if (!TextUtils.isEmpty(crashReport) && !SDKControler.isDebugMode()) {
                boolean crash = crashedBySDK(crashReport);

                if (crash) {// 崩溃由SDK引起
                    StaticsManager.sendSdkCrashStatics(crashReport, 1);
                } else {
                    StaticsManager.sendSdkCrashStatics(crashReport, 2);
                }
            }

        }
    }

    /**
     * 是否因为SDK引起的崩溃
     * 
     * @param crashReport
     * @return
     */
    private boolean crashedBySDK(String crashReport) {
        String[] sdkPackageNames = {
                "com.kugou.game.sdk", "com.kuyou.platform.ui.push", "com.kugou.framework",
                "com.kugou.download", "com.kugou.sdk"
        };
        if (!TextUtils.isEmpty(crashReport)) {
            for (String name : sdkPackageNames) {
                if (crashReport.contains(name)) {
                    return true;
                }
            }

        }
        return false;
    }

    /**
     * 设置崩溃日志是否已经上传
     * 
     * @param reported
     */
    private void setCrashReported(boolean reported) {
        mContext.getSharedPreferences("sdk_crash_reported_setting", Context.MODE_PRIVATE).edit()
                .putBoolean("reported", reported).commit();
    }

    /**
     * 崩溃日志是否已经上传
     * 
     * @return
     */
    private boolean isCrashReported() {
        return mContext.getSharedPreferences("sdk_crash_reported_setting", Context.MODE_PRIVATE)
                .getBoolean("reported", false);
    }

}
